package com.zrrd.yunchmall.product.service.impl;

import com.zrrd.yunchmall.product.entity.*;
import com.zrrd.yunchmall.product.service.*;
import com.zrrd.yunchmall.product.mapper.ProductMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author YeKong
 * @since 2024-01-15
 */
@Service
@SuppressWarnings("all")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private IProductAttributeValueService attributeValueService;
    @Autowired
    private IMemberPriceService memberPriceService;
    @Autowired
    private IProductLadderService ladderService;
    @Autowired
    private IProductFullReductionService fullReductionService;
    @Autowired
    private ISkuStockService skuStockService;

    /**
     * 重写MybatisPlus中的save方法
     */
    @Override
    @Transactional
    public boolean save(Product product) {
        //1.保存商品信息
        super.save(product);
        //2.保存商品属性值信息 ProductAttributeValue
        List<ProductAttributeValue> productAttributeValueList = product.getProductAttributeValueList();
        productAttributeValueList.forEach(item -> {
            item.setProductId(product.getId());//设置商品id
        });
        attributeValueService.saveBatch(productAttributeValueList);//将所有项批量添加
        //3.保存商品会员价格信息
        List<MemberPrice> memberPriceList = product.getMemberPriceList();
        memberPriceList.forEach(item -> {
            item.setProductId(product.getId());//设置商品id
        });
        memberPriceService.saveBatch(memberPriceList);
        //4.保存折扣信息
        List<ProductLadder> productLadderList = product.getProductLadderList();
        productLadderList.forEach(item -> {
            item.setProductId(product.getId());//设置商品id
        });
        ladderService.saveBatch(productLadderList);
        //5.保存满减信息
        List<ProductFullReduction> productFullReductionList = product.getProductFullReductionList();
        productFullReductionList.forEach(item -> {
            item.setProductId(product.getId());//设置商品id
        });
        fullReductionService.saveBatch(productFullReductionList);
        //6.添加SKU库存信息
        List<SkuStock> skuStockList = product.getSkuStockList();
        String skuCodePrefix = System.currentTimeMillis() + "";
        for (int i = 0; i < skuStockList.size(); i++) {
            skuStockList.get(i).setProductId(product.getId());
            String x = i < 10 ? ("0" + i) : ("" + i);
            skuStockList.get(i).setSkuCode(skuCodePrefix);
        }
        skuStockService.saveBatch(skuStockList);
        //7.保存商品信息操作日志
        //ProductOperateLog operateLog = new ProductOperateLog();

        return true;
    }
}
